//
//  JieTableViewController.swift
//  JieTableView
//
//  Created by jiezhang on 14-10-5.
//  Copyright (c) 2014年 jiezhang. All rights reserved.
//

import UIKit

class SelectPlantsController: UITableViewController {

    // default datas
    var datas:Int = 0
    
    var listVideos : NSMutableArray!

    
    override func viewDidLoad() {
        super.viewDidLoad()
        let bundle = NSBundle.mainBundle()
        let plistPath : String! = bundle.pathForResource("videos", ofType: "plist")
        listVideos = NSMutableArray(contentsOfFile: plistPath)
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        //下面这段话是设置左边编辑，右边添加item
        
        //self.navigationItem.leftBarButtonItem = self.editButtonItem()
        //let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "insertNewObject:")
        //self.navigationItem.rightBarButtonItem = addButton
        
        
        weak var weakSelf = self as SelectPlantsController
        
        // 上拉动画
        self.tableView.headerViewRefreshAnimationStatus(.headerViewRefreshArrowAnimation, images: [])
        
        self.tableView.hiddenFooterView()
        // 上啦加载更多
        self.tableView.toLoadMoreAction({ () -> () in
            print("toLoadMoreAction success")
            if (weakSelf?.datas < 10){
                weakSelf?.datas += 10
                weakSelf?.tableView.reloadData()
                weakSelf?.tableView.doneRefresh()
            }else{
                weakSelf?.tableView.endLoadMoreData()
            }
        })
        
        // 及时上拉刷新
        self.tableView.nowRefresh({ () -> Void in
            weakSelf?.delay(2.0, closure: { () -> () in})
            weakSelf?.delay(2.0, closure: { () -> () in
                print("nowRefresh success")
                weakSelf?.datas += 10
                self.tableView.showFooterView()
                weakSelf?.tableView.reloadData()
                weakSelf?.tableView.doneRefresh()
            })
        })
        
    }

    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    //返回节的个数
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }
    //返回某个节中的行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return listVideos.count
    }
    //为表视图单元格提供数据，该方法是必须实现的方法
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier : String = "videoItem"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! SelectPlantsCell
        let row = indexPath.row
        let rowDict : NSDictionary = listVideos.objectAtIndex(row) as! NSDictionary
        let url : String = rowDict.objectForKey("video_img") as! String
        let dataImg : NSData = NSData(contentsOfURL: NSURL(string : url)!)!
        //cell.JieVideoImg.image = UIImage(data: dataImg)
        cell.selectImage.image = UIImage(data: dataImg)
        cell.selectTitle.text = "红掌植物"
        cell.selectWendu.text = rowDict.objectForKey("video_title") as? String
        cell.selectShidu.text = rowDict.objectForKey("video_subTitle") as? String
        cell.selectGuangzhao.text = "6个小时"
        cell.selectYangfen.text = "每隔5天一次"
        return cell

    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let row = indexPath.row
        let rowDict : NSDictionary = listVideos.objectAtIndex(row) as! NSDictionary
        let url : String = rowDict.objectForKey("video_img") as! String
        
        let msg:String = "你选择的是\(url)"
        
        SweetAlert().showAlert(msg, subTitle: "已选择更换植物!", style: AlertStyle.Success)
    }
    
    // 支持单元格编辑功能
    //override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
    //    return true
    //}
    
    // Override to support editing the table view.
    //override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    //    if editingStyle == .Delete {
            // Delete the row from the data source
    //        listVideos.removeObjectAtIndex(indexPath.row)
    //        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    //    } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    //    }
    //}

    
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
        if fromIndexPath != toIndexPath{
            
            let object: AnyObject = listVideos.objectAtIndex(fromIndexPath.row)
            listVideos.removeObjectAtIndex(fromIndexPath.row)
            if toIndexPath.row > self.listVideos.count{
                self.listVideos.addObject(object)
            }else{
                self.listVideos.insertObject(object, atIndex: toIndexPath.row)
            }
        }
    }
    

    
    // Override to support conditional rearranging of the table view.
    //在编辑状态，可以拖动设置item位置
    //override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
    //    return true
    //}
    

    
    // MARK: - Navigation

    //给新进入的界面进行传值
    /*override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "showDetail" {
            if let indexPath = self.tableView.indexPathForSelectedRow {
                let object : NSDictionary = listVideos[indexPath.row] as! NSDictionary
                (segue.destinationViewController as! JieDetailViewController).detailItem = object
            }
        }
    }*/

    
    func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }
    

}
